﻿using HML.Design;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Drawing2D;
using System.Reflection;
using System.Windows.Forms;

namespace HML
{
    /// <summary>
    /// 横向渐变百分比控件
    /// </summary>
    [Description("横向渐变百分比控件")]
    [DefaultProperty("Value")]
    [DefaultEvent("ValueChanged")]
    [TypeConverter(typeof(PropertyOrderConverter))]
    [Designer(typeof(HGradualPercentageDesigner))]
    [ToolboxItem(true)]
    [ToolboxBitmap(typeof(HGradualPercentage), "Controls.GradualPercentage.Resources.HGradualPercentage.bmp")]
    public class HGradualPercentage : MainThreadAnimationControl, ISkinObject
    {
        #region 主题

        private SkinObjectXmlMetadata skinObjectXmlMetadata = null;
        /// <summary>
        /// 主题对象在主题文件信息
        /// </summary>
        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual SkinObjectXmlMetadata SkinObjectXmlMetadata
        {
            get
            {
                if (this.skinObjectXmlMetadata == null)
                    this.skinObjectXmlMetadata = new SkinObjectXmlMetadata(Assembly.GetAssembly(typeof(HGradualPercentage)).GetName().Name, typeof(HGradualPercentage).Name);

                return this.skinObjectXmlMetadata;
            }
        }

        private SkinController skinController = null;
        /// <summary>
        /// 主题控制器
        /// </summary>
        [Description("主题控制器")]
        [Category("杂项")]
        [PropertyOrder(-360)]
        [DefaultValue(null)]
        [RefreshProperties(RefreshProperties.All)]
        public virtual SkinController SkinController
        {
            get { return this.skinController; }
            set
            {
                if (this.skinController == value)
                    return;

                if (this.skinController != null)
                    this.skinController.RemoveSkinObject(this);

                this.skinController = value;

                if (this.skinController != null)
                    this.skinController.AddSkinObject(this);
            }
        }

        private SkinEnabledState skinEnabled= SkinEnabledState.Auto;
        /// <summary>
        /// 主题是否启用
        /// </summary>
        [Description("主题是否启用")]
        [Category("杂项")]
        [PropertyOrder(-300)]
        [DefaultValue(SkinEnabledState.Auto)]
        [RefreshProperties(RefreshProperties.All)]
        public virtual SkinEnabledState SkinEnabled
        {
            get { return this.skinEnabled; }
            set
            {
                if (this.skinEnabled == value)
                    return;

                this.skinEnabled = value;
                this.OnSkinChanged();
            }
        }

        private SkinStyle skinStyle = SkinStyle.Normal;
        /// <summary>
        /// 主题风格
        /// </summary>
        [Description("主题风格")]
        [Category("杂项")]
        [PropertyOrder(-260)]
        [DefaultValue(SkinStyle.Normal)]
        [RefreshProperties(RefreshProperties.All)]
        public virtual SkinStyle SkinStyle
        {
            get { return this.skinStyle; }
            set
            {
                if (this.skinStyle == value)
                    return;

                this.skinStyle = value;
                this.OnSkinChanged();
            }
        }

        private StyleAppearanceObject stateAppearance;
        /// <summary>
        /// 风格外观
        /// </summary>
        [Description("风格外观")]
        [Category("杂项")]
        [PropertyOrder(-200)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public StyleAppearanceObject StyleAppearance
        {
            get
            {
                if (this.stateAppearance == null)
                    this.stateAppearance = new StyleAppearanceObject(this, null);
                return this.stateAppearance;
            }
        }

        /// <summary>
        /// 主题已更改
        /// </summary>
        public virtual void OnSkinChanged()
        {
            SkinManager.SyncSkinValueToProperty(this);
            this.Invalidate();
        }

        private ISkinObject followSkinObject = null;
        /// <summary>
        /// 主题设置跟随指定主题对象（自己的设置不再生效，提供给代码使用）
        /// </summary>
        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        [Localizable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual ISkinObject FollowSkinObject
        {
            get { return this.followSkinObject; }
            set
            {
                if (this.followSkinObject == value)
                    return;

                this.followSkinObject = value;
                this.OnSkinChanged();
            }
        }

        public virtual bool GetSkinObjectSkinStateCore()
        {
            return SkinManager.GetSkinObjectSkinState(this.FollowSkinObject ?? this);
        }

        void ISkinObject.InitializeInvalidate()
        {
            throw new NotImplementedException();
        }

        void ISkinObject.Invalidate()
        {
            this.Invalidate();
        }

        #endregion

        #region 新增事件

        private static readonly object EventValueChanged = new object();
        /// <summary>
        /// Value值更改事件
        /// </summary>
        [Description("Value值更改事件")]
        public event EventHandler ValueChanged
        {
            add { Events.AddHandler(EventValueChanged, value); }
            remove { Events.RemoveHandler(EventValueChanged, value); }
        }

        #endregion

        #region 停用事件

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event EventHandler PaddingChanged
        {
            add { base.PaddingChanged += value; }
            remove { base.PaddingChanged -= value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event EventHandler TabIndexChanged
        {
            add { base.TabIndexChanged += value; }
            remove { base.TabIndexChanged -= value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event EventHandler TabStopChanged
        {
            add { base.TabStopChanged += value; }
            remove { base.TabStopChanged -= value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event EventHandler TextChanged
        {
            add { base.TextChanged += value; }
            remove { base.TextChanged -= value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event EventHandler RightToLeftChanged
        {
            add { base.RightToLeftChanged += value; }
            remove { base.RightToLeftChanged -= value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event EventHandler ImeModeChanged
        {
            add { base.ImeModeChanged += value; }
            remove { base.ImeModeChanged -= value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event EventHandler BackgroundImageChanged
        {
            add { base.BackgroundImageChanged += value; }
            remove { base.BackgroundImageChanged -= value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event EventHandler BackgroundImageLayoutChanged
        {
            add { base.BackgroundImageLayoutChanged += value; }
            remove { base.BackgroundImageLayoutChanged -= value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event EventHandler BackColorChanged
        {
            add { base.BackColorChanged += value; }
            remove { base.BackColorChanged -= value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event EventHandler ForeColorChanged
        {
            add { base.ForeColorChanged += value; }
            remove { base.ForeColorChanged -= value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event EventHandler Click
        {
            add { base.Click += value; }
            remove { base.Click -= value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event EventHandler DoubleClick
        {
            add { base.DoubleClick += value; }
            remove { base.DoubleClick -= value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event MouseEventHandler MouseClick
        {
            add { base.MouseClick += value; }
            remove { base.MouseClick -= value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new event MouseEventHandler MouseDoubleClick
        {
            add { base.MouseDoubleClick += value; }
            remove { base.MouseDoubleClick -= value; }
        }
        #endregion

        #region 新增属性

        private bool animationEnabled = false;
        /// <summary>
        /// Value改变时是否采用动画方式
        /// </summary>
        [Description("Value改变时是否采用动画方式")]
        [Category("杂项")]
        [PropertyOrder(-199)]
        [DefaultValue(false)]
        public bool AnimationEnabled
        {
            get { return this.animationEnabled; }
            set
            {
                if (this.animationEnabled == value)
                    return;

                this.animationEnabled = value;
                if (!this.animationEnabled)
                {
                    this.animation_current_value = this.Value;
                    MainThreadAnimationControl.AnimationStop(this);
                    this.Invalidate();
                }
            }
        }

        private int animationTime = 70;
        /// <summary>
        /// Value改变时使用动画的时间(毫秒)
        /// </summary>
        [Description("Value改变时使用动画的时间(毫秒)")]
        [Category("杂项")]
        [PropertyOrder(-198)]
        [DefaultValue(70)]
        public int AnimationTime
        {
            get { return this.animationTime; }
            set
            {
                if (this.animationTime == value || value <= 0)
                    return;

                this.animationTime = value;
            }
        }

        private int gridsSize = 6;
        /// <summary>
        /// 网格大小（像素）
        /// </summary>
        [Description("网格大小（像素）")]
        [PropertyOrder(-197)]
        [DefaultValue(6)]
        public int GridsSize
        {
            get { return this.gridsSize; }
            set
            {
                if (this.gridsSize == value || value < 1)
                    return;

                this.gridsSize = value;
                this.Invalidate();
            }
        }

        private GradualPercentageColorCollection gradualColorsCollection;
        /// <summary>
        /// 渐变颜色集合
        /// </summary>
        [Description("渐变颜色集合")]
        [PropertyOrder(-195)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public GradualPercentageColorCollection GradualColors
        {
            get
            {
                if (this.gradualColorsCollection == null)
                    this.gradualColorsCollection = new GradualPercentageColorCollection(this);
                return this.gradualColorsCollection;
            }
        }

        private double value = 0D;
        /// <summary>
        /// 百分比(0-100)
        /// </summary>
        [Description("百分比")]
        [PropertyOrder(-194)]
        [DefaultValue(0D)]
        public double Value
        {
            get { return this.value; }
            set
            {
                if (value < 0)
                    value = 0;
                if (value > 100)
                    value = 100;
                if (this.value == value)
                    return;

                this.value = value;
                if (this.AnimationEnabled && this.Enabled && this.Visible && this.DesignMode == false && this.Parent != null)
                {
                    this.animation_start_value = this.animation_current_value;
                    this.animation_current_value = this.animation_start_value;
                    this.animation_end_value = value;

                    this.usedTime = 0;
                    MainThreadAnimationControl.AnimationStart(this);
                    this.Invalidate();
                }
                else
                {
                    this.animation_current_value = value;
                    this.Invalidate();
                }

                this.OnValueChanged(EventArgs.Empty);
            }
        }

        #endregion

        #region 重写属性

        protected override Size DefaultSize
        {
            get { return new Size(162, 40); }
        }

        protected override ImeMode DefaultImeMode
        {
            get { return ImeMode.Disable; }
        }

        #endregion

        #region 停用属性

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public new Padding Padding
        {
            get { return base.Padding; }
            set { base.Padding = value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new int TabIndex
        {
            get { return base.TabIndex; }
            set { base.TabIndex = value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public new bool TabStop
        {
            get { return base.TabStop; }
            set { base.TabStop = value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override string Text
        {
            get { return base.Text; }
            set { base.Text = value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override Font Font
        {
            get { return base.Font; }
            set { base.Font = value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override RightToLeft RightToLeft
        {
            get { return base.RightToLeft; }
            set { base.RightToLeft = value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public new ImeMode ImeMode
        {
            get { return base.ImeMode; }
            set { base.ImeMode = value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override Image BackgroundImage
        {
            get { return base.BackgroundImage; }
            set { base.BackgroundImage = value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override ImageLayout BackgroundImageLayout
        {
            get { return base.BackgroundImageLayout; }
            set { base.BackgroundImageLayout = value; }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override Color BackColor
        {
            get { return this.StyleAppearance.BackColor; }
            set { }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override Color ForeColor
        {
            get { return this.StyleAppearance.TextColor; }
            set { }
        }

        #endregion

        #region 字段

        /// <summary>
        /// 动画开始值
        /// </summary>
        private double animation_start_value = 0f;
        /// <summary>
        /// 动画结束值
        /// </summary>
        private double animation_end_value = 0f;
        /// <summary>
        /// 动画当前值
        /// </summary>
        private double animation_current_value = 0f;
        /// <summary>
        /// 动画已使用的时间
        /// </summary>
        private double usedTime = 0;

        #endregion

        public HGradualPercentage()
        {
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            SetStyle(ControlStyles.StandardClick, false);
            SetStyle(ControlStyles.StandardDoubleClick, false);
            SetStyle(ControlStyles.Selectable, false);

            this.TabStop = false;
            this.OnSkinChanged();
        }

        #region 重写

        protected override void OnScaleDpiChangedInitialize()
        {
            this.Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Graphics g = e.Graphics;

            int scale_gridsSize = (int)Math.Ceiling(this.GridsSize * this.ScaleDpi);
            int len = this.GradualColors.Count;

            //渐变
            if (len > 0 && this.ClientRectangle.Width > 0 && this.ClientRectangle.Height > 0)
            {
                Color[] colors = new Color[Math.Max(2, len + 1)];
                float[] positions = new float[Math.Max(2, len + 1)];
                for (int i = 0; i < len; i++)
                {
                    colors[i] = this.GradualColors[i].Color;
                    positions[i] = this.GradualColors[i].Position;
                }
                if (len == 1)
                {
                    colors[1] = this.GradualColors[0].Color;
                    positions[1] = 1;
                }
                positions[0] = 0;
                positions[positions.Length - 1] = 1;

                float realityWidth = this.ClientRectangle.Width * (float)this.animation_current_value / 100f;
                LinearGradientBrush lgb = new LinearGradientBrush(new RectangleF(0, 0, this.ClientRectangle.Width + 1, this.ClientRectangle.Height), Color.Transparent, Color.Transparent, 0, true) { InterpolationColors = new ColorBlend() { Positions = positions, Colors = colors } };
                g.FillRectangle(lgb, 0, 0, realityWidth, this.ClientRectangle.Height);
                lgb.Dispose();
            }

            //网格
            int count = (int)Math.Ceiling(this.ClientRectangle.Width / (float)scale_gridsSize);
            Pen grids_pen = new Pen(this.StyleAppearance.GridsColor);
            for (int i = 0; i < count; i++)
            {
                int x = (int)(this.ClientRectangle.X + scale_gridsSize * i);
                g.DrawLine(grids_pen, x, this.ClientRectangle.Y, x, this.ClientRectangle.Height);
            }
            g.DrawLine(grids_pen, this.ClientRectangle.X, this.ClientRectangle.Height / 2, this.ClientRectangle.Right, this.ClientRectangle.Height / 2);
            g.DrawRectangle(grids_pen, this.ClientRectangle.X, this.ClientRectangle.Y, this.ClientRectangle.Width - 1, this.ClientRectangle.Height - 1);
            grids_pen.Dispose();
        }

        protected override void OnEnabledChanged(EventArgs e)
        {
            base.OnEnabledChanged(e);

            if (this.DesignMode)
                return;

            if (!this.Enabled)
            {
                this.animation_current_value = this.Value;
                MainThreadAnimationControl.AnimationStop(this);
            }
        }

        protected override void OnVisibleChanged(EventArgs e)
        {
            base.OnVisibleChanged(e);

            if (this.DesignMode)
                return;

            if (!this.Visible)
            {
                this.animation_current_value = this.Value;
                MainThreadAnimationControl.AnimationStop(this);
            }
        }

        protected override void OnParentChanged(EventArgs e)
        {
            base.OnParentChanged(e);

            if (this.DesignMode)
                return;

            if (!this.Visible)
            {
                this.animation_current_value = this.Value;
                MainThreadAnimationControl.AnimationStop(this);
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                MainThreadAnimationControl.AnimationStop(this);
            }
            base.Dispose(disposing);
        }

        /// <summary>
        /// 动画控件动画中要处理的内容(不能时耗时操作)
        /// </summary>
        /// <param name="interval">动画定时器间隔时间</param>
        protected override void Animationing(int interval)
        {
            bool finish = false;
            this.usedTime += interval;
            if (this.usedTime > this.AnimationTime)
            {
                this.usedTime = this.AnimationTime;
                MainThreadAnimationControl.AnimationStop(this);
                finish = true;
            }

            double progress = this.usedTime / this.AnimationTime;
            if (finish)
            {
                if (progress < 0)
                    progress = 0;
                if (progress > 1)
                    progress = 1;

                this.usedTime = 0;
            }

            this.animation_current_value = this.animation_start_value + (this.animation_end_value - this.animation_start_value) * progress;
            this.Invalidate();
        }

        #endregion

        #region 虚方法

        protected virtual void OnValueChanged(EventArgs e)
        {
            EventHandler handler = Events[EventValueChanged] as EventHandler;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        #endregion

        #region 外观

        public class StyleAppearanceObject : AppearanceObjectBase
        {
            internal StyleAppearanceObject(ISkinObject owner, AppearanceObjectBase parent) : base(owner, parent) { }

            #region 属性

            private Color skinBackColor = Color.Empty;
            private readonly Color defaultBackColor = SystemColors.Control;
            private Color backColor = Color.Empty;
            /// <summary>
            /// 背景颜色
            /// </summary>
            [Description("背景颜色")]
            [PropertyOrder(-195)]
            [SkinProperty(true, true)]
            public Color BackColor
            {
                get
                {
                    if (this.owner.GetSkinObjectSkinStateCore() && this.skinBackColor != Color.Empty)
                    {
                        return this.skinBackColor;
                    }

                    if (this.backColor != Color.Empty)
                    {
                        return this.backColor;
                    }

                    if (((Control)this.owner).Parent != null)
                    {
                        return ((Control)this.owner).Parent.BackColor;
                    }

                    return this.defaultBackColor;
                }
                set
                {
                    if (this.backColor == value)
                        return;

                    this.backColor = value;
                    this.Invalidate();
                }
            }
            private bool ShouldSerializeBackColor()
            {
                return this.backColor != Color.Empty;
            }
            private void ResetBackColor()
            {
                this.backColor = Color.Empty;
                this.Invalidate();
            }

            private Color skinTextColor = Color.Empty;
            private readonly Color defaultTextColor = SystemColors.ControlText;
            private Color textColor = Color.Empty;
            /// <summary>
            /// 文本颜色
            /// </summary>
            [Description("文本颜色")]
            [PropertyOrder(-194)]
            [SkinProperty(true, true)]
            public Color TextColor
            {
                get
                {
                    if (this.owner.GetSkinObjectSkinStateCore() && this.skinTextColor != Color.Empty)
                    {
                        return this.skinTextColor;
                    }

                    if (this.textColor != Color.Empty)
                    {
                        return this.textColor;
                    }

                    if (((Control)this.owner).Parent != null)
                    {
                        return ((Control)this.owner).Parent.ForeColor;
                    }

                    return this.defaultTextColor;
                }
                set
                {
                    if (this.textColor == value)
                        return;

                    this.textColor = value;
                    this.Invalidate();
                }
            }
            private bool ShouldSerializeTextColor()
            {
                return this.textColor != Color.Empty;
            }
            private void ResetTextColor()
            {
                this.textColor = Color.Empty;
                this.Invalidate();
            }

            private Color skinGridsColor = Color.Empty;
            private readonly Color defaultGridsColor = SystemColors.ControlDark;
            private Color gridsColor = Color.Empty;
            /// <summary>
            /// 网格颜色
            /// </summary>
            [Description("网格颜色")]
            [PropertyOrder(-193)]
            [SkinProperty(true, false)]
            public Color GridsColor
            {
                get
                {
                    if (this.owner.GetSkinObjectSkinStateCore())
                    {
                        return this.skinGridsColor;
                    }

                    if (this.gridsColor != Color.Empty)
                    {
                        return this.gridsColor;
                    }

                    return this.defaultGridsColor;
                }
                set
                {
                    if (this.gridsColor == value)
                        return;

                    this.gridsColor = value;
                    this.Invalidate();
                }
            }
            private bool ShouldSerializeGridsColor()
            {
                return this.gridsColor != Color.Empty;
            }
            private void ResetGridsColor()
            {
                this.gridsColor = Color.Empty;
                this.Invalidate();
            }

            #endregion

        }

        #endregion

    }
}
